<?php
namespace app\index\controller;

use think\Validate;
use think\Db;
use app\index\controller\IndexBase;

class User extends IndexBase
{

    public $except_action = ['getSellerInfo'];

    public function _initialize()
    {
        parent::_initialize();
    }
    public function index()
    {
        $userinfo = model('UserInfo')->where('user_id', $this->user_id)->find();
        if (empty($userinfo)) {
            model('UserInfo')->insert(['user_id' => $this->user_id]);
            $userinfo = model('UserInfo')->where('user_id', $this->user_id)->find();
        }
        $userinfo->email = is_login('email');
        $userinfo->username = is_login('username');
        $page = ['title' => '用户中心 - 天佑二手货 - 天佑工作室'];
        return view('', ['userinfo' => $userinfo, 'page' => $page]);
    }

    /**
     * 修改昵称接口
     * @author cuibo weiai525@outlook.com at 2016-07-20 23:08:07
     */
    public function modifyUserName()
    {
        $data = input('get.');
        // 字段验证
        $Validate = validate('User');
        if (!$Validate->scene('modify_username')->check($data)) {
            return $this->error($Validate->getError());
        }

        // 修改时间验证
        $user = model('User');
        $last_modifyname_time = $user->where('user_id', $this->user_id)->value('last_modifyname_time');
        if (time() <= strtotime('+6 Month', $last_modifyname_time)) {
            return $this->error('修改失败,6个月只能修改一次昵称');
        }

        // 数据写入
        $savedata = [
            'username' => $data['username'],
            'last_modifyname_time' => time(),
        ];
        // 用update方法不会自动刷新update字段 故改用save方法更新数据
        if ($user->save($savedata, ['user_id' => $this->user_id]) === false) {
            return $this->error('修改失败,系统开小差了');
        }

        return $this->success('修改成功');
    }

    /**
     * 设置保密级别
     * @author cuibo weiai525@outlook.com at 2016-07-20 23:08:07
     */
    public function setProtect()
    {
        $data = input('get.');
        $Validate = new Validate([
            'protect' => 'require|in:1,2,3,4',
        ]);
        if (!$Validate->check($data)) {
            return $this->error($Validate->getError());
        }
        if (model('UserInfo')->where('user_id', $this->user_id)->update(['protect' => $data['protect']]) > -1) {
            return $this->success('修改成功');
        }
        return $this->error('修改失败');
    }

    /**
     * 修改头像接口
     * @author cuibo weiai525@outlook.com at 2016-07-20 23:08:07
     */
    public function modifyImage()
    {
        $photo = input('photo', 'photo');
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $photo, $result)) {
            $base64 = str_replace($result[1], '', $photo);
            $image = base64_decode($base64);
            if ($image) {
                $imageInfo = getimagesizefromstring($image);
                if ($imageInfo[0] == $imageInfo[1] && $imageInfo[0] == 300 && in_array($imageInfo['mime'], ['image/png', 'image/jpg', 'image/bmp', 'image/jpeg']) && strlen($image) / 1024 / 1024 <= 2) {
                    $filename = md5($this->user_id) . '.' . substr($imageInfo['mime'], 6);
                    $path = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'avatar' . DS;
                    if (!file_exists($path)) {
                        mkdir($path);
                    }
                    file_put_contents($path . $filename, $image);
                    model('userInfo')->where('user_id', $this->user_id)->update(['image' => $filename]);
                    return $this->success('头像修改成功');
                } else {
                    return $this->error('头像格式不对');
                }
            }
            return $this->error('头像格式不对');
        } else {
            return $this->error('头像格式不对');
        }
    }

    /**
     * 用户中心修改密码接口
     */
    public function modifyPassword()
    {

        if (request()->isPost()) {
            $data = input('post.');
            // 验证字段合法性
            $validate = validate('User');
            if ($validate->scene('modify_password')->check($data)) {
                /// 查找密码和邮箱
                $user = model('User')->where('user_id', $this->user_id)->field('password,email')->find();
                // 验证原始密码
                if ($user->password != password($user->email . $data['oldpassword'])) {
                    return $this->error("原始密码错误");
                }
                if (model('User')->save(['password' => password($user['email'] . $data['password'])], ['user_id' => $this->user_id]) === false) {
                    return $this->error('服务器出错，请重试');
                }
                // 修改成功则退出登录，暂定直接清除session，cookie，
                session('email', null);
                cookie('remember_token', null);
                return $this->success('密码修改成功！请重新登陆', url('auth/login'));
            } else {
                return $this->error($validate->getError());
            }
        }
    }

    public function getSellerInfo($user_id = 0)
    {
        $db_prefix = config('database.prefix');
        $table1 = $db_prefix.'user';
        $table2 = $db_prefix.'user_info';
        $data = Db::name('user')->where($table1.'.user_id',$user_id)->join($table2,$table1.'.user_id = '.$table2.'.user_id','LEFT')->select();
        if (empty($data)) {
            return $this->error('用户不存在');
        }
        $user = $data[0];
        /*严格保护：任何情况下不能查看自己的姓名、电话、地址、邮箱；4
        一般：只有登陆后的用户能够查看自己的姓氏、电话、地址、邮箱；2
        增强模式：在一般的基础上，不能查看自己的电话；3
        不保护：所有人都可查看自己的姓氏、地址、邮箱(不包括电话)；1*/
        $info['code'] = 1;
        $info['msg'] = '';
        $info['protect'] = $user['protect'];
        $info['user_id'] = $user['user_id'];
        $info['username'] = $user['username'];
        $info['name'] = '';
        $info['email'] = '';
        $info['phone'] = '';
        $info['address'] = '';
        switch ($user['protect']) {
            case 1:
                $info['protect'] = '不保护';
                $info['name'] = $user['name'];
                $info['address'] = $user['address'];
                $info['email'] = $user['email'];
                break;
            case 2:
                $info['protect'] = '一般模式';
                $info['name'] = $user['name'];
                $info['address'] = $user['address'];
                $info['phone'] = $user['phone'];
                $info['email'] = $user['email'];
                break;
            case 3:
                $info['protect'] = '增强模式';
                if (is_login() !== false) {
                    $info['name'] = $user['name'];
                    $info['address'] = $user['address'];
                    $info['email'] = $user['phone'];
                }
                break;
            case 4:
                $info['protect'] = '严格保护';
                break;
            default:
                break;
        }
        return json($info);
    }
}
